<template>
  <div style="position:relative">
    <!-- :params="fetchParams" -->
    <FilterTable
      ref="table"
      :columns="columns"
      :dataSource="list"
      :height="200"
      :isColumnFilter="false"
      :isToperInfo="false"
      :isSelectColumn="false"
      :onSyncTableData="syncTableFun"
      :onCellChange="onCellChange"
      :onColumnsChange="columns => (this.columns = columns)"
    >
      <template slot="controls">
        <el-button size="small" type="primary" icon="el-icon-plus" @click="addPjxmHandle()">新增</el-button>
      </template>
    </FilterTable>
    <BaseDialog :visible.sync="visiblePjxm" title="备件选择" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }" destroyOnClose>
      <AddPjxm ref="addPjxm" @closePj="closeAdddpjxm" />
    </BaseDialog>
  </div>
</template>
<script>
import AddPjxm from '../addXM/addpjxm';
import { dictionary } from '@/utils/dictMixin';
import { getStorageList, getPartitionList, detailsPjxm } from '@/api/repair/repair/activitesManage';
let _this;
export default {
  name: 'Pjxm',
  components: {
    AddPjxm
  },
  mixins: [dictionary],
  props: ['type', 'detaildata', 'dataList', 'labourSfqfChangeData'],
  data() {
    // this.BaseTable = null;
    return {
      total: 0,
      visiblePjxm: false,
      columns: this.createTable(),
      fetchApi: '',
      // fetchParams: { xhrAbort: false},
      list: [],
      tableData: [],
      editItems: [],
      propsList: [],
      onSyncTableData: null
    };
  },
  watch: {
    dataList(val) {
      this.insertRecords(val);
    },
    labourSfqfChangeData(val) {
      console.log('进入跟新收费区分', val);
      this.changeSfqfHandleData(val);
    }
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
    this.insertRecords(this.dataList);
    this.changeSfqfHandleData(this.labourSfqfChangeData);
  },
  created() {
    _this = this;
    _this.getPartitionList();
    _this.getStorageList();
    if (_this.type == 2) {
      _this.detailsPjxm();
    }
  },
  methods: {
    // 表格数据变化时
    onCellChange(keys, obj) {
      console.log(keys, obj, 'keys');
      console.log(keys[Object.keys(keys)[0]], '修改后对应的编码');
      const targetKey = Object.keys(keys)[0].split('|')[1];
      // 备件 关联 项目收费区分
      console.log('1111111', keys);
      if (targetKey === 'LABOUR_CODE') {
        const val = Object.values(keys)[0].substr(-36);
        if (obj.LABOUR_CODE == '') {
          this.BaseTable.SET_CELL_DISABLED(obj, 'CHARGE_PARTITION_CODE', false);
        } else {
          this.BaseTable.SET_CELL_DISABLED(obj, 'CHARGE_PARTITION_CODE', true);
        }

        console.log('备件选择维修项目', val);
        // obj.CHARGE_PARTITION_CODE = this.propsList[val].CHARGE_PARTITION_CODE;
        for (const prp of this.propsList) {
          if (prp.UID_HIDDEN == val) {
            obj.CHARGE_PARTITION_CODE = prp.CHARGE_PARTITION_CODE;
          }
        }
        console.log('维修项目数据列表', this.propsList);
      }
      // PART_QUANTITY   备件数量
      // PART_SALES_PRICE备件销售单价
      // PART_SALES_AMOUNT备件销售金额
      // DISCOUNT折扣率
      // PART_SALES_AMOUNT_DISCOUNT折扣后金额合计
      if (isNaN(Number(this.list[obj.$index].PART_QUANTITY)) && isNaN(Number(this.list[obj.$index].PART_SALES_PRICE))) {
        this.list[obj.$index].PART_SALES_AMOUNT = 0;
        this.list[obj.$index].PART_SALES_AMOUNT_DISCOUNT = 0;
      } else {
        this.list[obj.$index].PART_SALES_AMOUNT = Number(this.list[obj.$index].PART_QUANTITY) * Number(this.list[obj.$index].PART_SALES_PRICE);
        if (isNaN(Number(this.list[obj.$index].DISCOUNT))) {
          this.list[obj.$index].PART_SALES_AMOUNT_DISCOUNT = 0;
        } else {
          this.list[obj.$index].PART_SALES_AMOUNT_DISCOUNT = Number(this.list[obj.$index].PART_SALES_AMOUNT) * Number(this.list[obj.$index].DISCOUNT);
        }
      }
      if(obj.CHARGE_PARTITION_CODE == 'S' || obj.CHARGE_PARTITION_CODE == 'N'){
        obj.PART_SALES_AMOUNT_DISCOUNT = 0.00;
      }   
      //  这里就开始计算total   用来储存
      this.total = 0;
      this.list.forEach(x => {
        this.total = this.total + Number(x.PART_SALES_AMOUNT_DISCOUNT);
      });

      this.$emit('handlepjxmTotal', this.total);
    },
    // 仓库名称下拉框
    async getStorageList() {
      const res = await getStorageList();
      this.columns.find(x => x.dataIndex === 'STORAGE_CODE').editItems = res.data.map(x => ({ value: x.STORAGE_CODE, text: x.STORAGE_NAME }));
    },
    // 获取收费区分下拉框
    async getPartitionList() {
      const res = await getPartitionList();
      this.columns.find(x => x.dataIndex === 'CHARGE_PARTITION_CODE').editItems = res.data.map(x => ({ value: x.CHARGE_PARTITION_CODE, text: x.CHARGE_PARTITION_NAME }));
    },
    // 获取维修材料方法
    async detailsPjxm() {
      let res = await detailsPjxm(_this.detaildata);
      // PART_QUANTITY   备件数量
      // PART_SALES_PRICE备件销售单价
      // PART_SALES_AMOUNT备件销售金额
      // DISCOUNT折扣率
      // PART_SALES_AMOUNT_DISCOUNT折扣后金额合计
      res.data.rows.forEach(x => {
        // x.SALES_PRICE = x.PART_SALES_PRICE
        if (isNaN(Number(x.DISCOUNT))) {
          x.PART_SALES_AMOUNT_DISCOUNT = 0;
        } else {
          x.PART_SALES_AMOUNT_DISCOUNT = Number(x.PART_SALES_AMOUNT) * Number(x.DISCOUNT);
        }
        if(x.CHARGE_PARTITION_CODE == 'S'||x.CHARGE_PARTITION_CODE == 'N'){
          x.PART_SALES_AMOUNT_DISCOUNT = 0;
        }
      });
      res.data.rows.forEach(x => {
        x.LABOUR_CODE = x.UID_HIDDEN;
        // += '~' + x.UID_HIDDEN;
      });
      _this.$refs.table.$refs.pageTable.EXECUTE_INSERT(res.data.rows);
    },
    ceshi(val) {
      _this.$emit('changetwo', _this.list);
    },
    // 传给父组件的数据
    syncTableFun(val) {
      this.onSyncTableData = val;
      this.tableData = val;
    },
    // 关闭子弹框
    closeAdddpjxm(val) {
      // this.getStorageList()
      if (val != false) {
        let pd1 = false;
        let pd2 = false;
        if (this.list.length > 0) {
          this.list.forEach(x => {
            if (x.PART_NO == val[0].PART_NO && x.STORAGE_CODE == val[0].STORAGE_CODE) {
              pd1 = true;
            }
            if (x.PART_NAME == val[0].PART_NAME && x.STORAGE_CODE == val[0].STORAGE_CODE) {
              pd2 = true;
            }
          });
        }
        if (pd1 && pd2) {
          this.$notify.error({
            title: '错误',
            message: '请勿重复提交'
          });
          return;
        }
        if (val[0].CLAIM_PRICE == null) {
          val[0].CLAIM_PRICE = 0;
        }
        val[0].PART_COST_AMOUNT = val[0].COST_AMOUNT;
        val[0].PART_COST_PRICE = val[0].COST_PRICE;
        this.visiblePjxm = false;
        val[0].DISCOUNT = 1;
        val[0].PART_QUANTITY = 1;
        if (val[0].SALES_PRICE != null) {
          val[0].PART_SALES_PRICE = Number(val[0].SALES_PRICE);
          val[0].PART_SALES_AMOUNT = val[0].PART_SALES_PRICE;
          val[0].PART_SALES_AMOUNT_DISCOUNT = val[0].PART_SALES_AMOUNT;
        } else {
          val[0].PART_SALES_AMOUNT = 0;
          val[0].PART_SALES_AMOUNT_DISCOUNT = 0;
        }
        val[0].REAL_UNIT_NAME = val[0].UNIT_NAME;
        this.$refs.table.$refs.pageTable.EXECUTE_INSERT(val);
        //  这里就开始计算total   用来储存
        this.total = 0;
        this.list.forEach(x => {
          this.total = this.total + Number(x.PART_SALES_AMOUNT_DISCOUNT);
        });
        this.$emit('handlepjxmTotal', this.total);
      } else if (val == false) {
        this.visiblePjxm = false;
      }
    },
    // 打开子弹框
    addPjxmHandle() {
      this.visiblePjxm = true;
    },
    // 维修材料表单数据删除
    delete(val) {
      this.$confirm('此操作将删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$refs.table.$refs.pageTable.EXECUTE_DELETE([val]);
          this.fetchParams = { ...this.fetchParams };
          //  这里就开始计算total   用来储存
          this.total = 0;
          this.list.forEach(x => {
            this.total = this.total + Number(x.PART_SALES_AMOUNT_DISCOUNT);
          });
          // 再写个方法传删除数据
          if (val.ITEM_ID != null && val.ITEM_ID != '' && val.ITEM_ID != undefined) {
            this.$emit('handleDeleted', val);
          }
          this.$emit('handlepjxmTotal', this.total);
        })
        .catch(() => {});
    },
    createTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          fixed: 'left',
          render: props => {
            // return <span>{props.row.index + 1}</span>;
            return <span>{props.$index + 1}</span>;
          }
        },
        {
          title: '操作',
          fixed: 'left',
          dataIndex: 'column-action',
          render: props => {
            return (
              <el-button size="mini" type="text" onClick={() => this.delete(props.row)}>
                删除
              </el-button>
            );
          }
        },
        {
          title: '仓库代码',
          dataIndex: 'STORAGE_CODE',
          sorter: true,
          filterItems: [],
          editable: true,
          editType: 'select',
          editItems: [],
          disabled: true
          // render: props => {
          //   return <span>{this.func(props.row.STORAGE_CODE,2)}</span>;
          //   }
        },
        {
          title: '备件代码',
          dataIndex: 'PART_NO',
          sorter: true
        },
        {
          title: '备件名称',
          dataIndex: 'PART_NAME',
          sorter: true
        },
        {
          title: '收费区分',
          dataIndex: 'CHARGE_PARTITION_CODE',
          sorter: true,
          filterItems: [],
          editable: true,
          editType: 'select',
          editItems: [],
          editRequired: true,
          disabled: false
        },
        {
          title: '主要备件',
          dataIndex: 'IS_MAIN_PART',
          sorter: true,
          editable: true,
          editType: 'select',
          editItems: this.createDictList('1004')
        },
        {
          title: '项目名称',
          dataIndex: 'LABOUR_CODE',
          sorter: true,
          editable: true,
          editType: 'select',
          editItems: []
        },
        {
          title: '计量单位名称',
          dataIndex: 'UNIT_CODE',
          sorter: true,
          render: props => {
            return <span>{this.list[props.row.index].REAL_UNIT_NAME}</span>;
          }
        },
        {
          title: '备件数量',
          dataIndex: 'PART_QUANTITY',
          sorter: true,
          editable: true,
          editType: 'number',
          min: 0,
          precision: 2
        },
        {
          title: '备件销售单价',
          dataIndex: 'PART_SALES_PRICE',
          sorter: true,
          summation: true,
          editable: true,
          editType: 'number',
          min: 0,
          precision: 2
        },
        {
          title: '备件销售金额',
          dataIndex: 'PART_SALES_AMOUNT',
          sorter: true,
          precision: 2,
          summation: true
        },
        {
          title: '折扣率',
          dataIndex: 'DISCOUNT',
          sorter: true,
          editable: true,
          editType: 'number',
          max: 1,
          min: 0,
          precision: 2
        },
        {
          title: '折扣后金额合计',
          dataIndex: 'PART_SALES_AMOUNT_DISCOUNT',
          sorter: true,
          precision: 2,
          summation: true
        },
        {
          title: '最新进货价',
          dataIndex: 'LATEST_PRICE', // LATEST_PRICE  目前   要修改的值。。。
          sorter: true,
          precision: 2,
          summation: true
        },
        {
          title: '销售单价',
          dataIndex: 'SALES_PRICE',
          sorter: true,
          min: 0,
          precision: 2,
          summation: true
        },
        {
          title: '备件成本单价',
          dataIndex: 'PART_COST_PRICE', // COST_PRICE
          sorter: true,
          precision: 2,
          summation: true
        },
        {
          title: '备件成本金额',
          dataIndex: 'PART_COST_AMOUNT', // COST_AMOUNT
          sorter: true,
          precision: 2,
          summation: true
        }
      ];
    },
    async getFwhdPjxmList(row) {
      const res = await getFwhdPjxmList(row, {
        creditTimes: 1.0,
        afterlabour: 0,
        zkAmountLabour: 0,
        afterDiscountAmountPart: 0,
        zkAmountPart: 0,
        fag: 'U',
        labourList: '',
        partList: '',
        subjoinList: '',
        modelList: '',
        vehicleList: '',
        order: 'asc',
        limit: 10,
        offset: 0,
        dmsFuncId: 35100010,
        _: 1565681747515
      });
      this.list = res.rows;
    },
    async getFwhdCkdmList() {
      const res = await getFwhdCkdmList();
      this.columns[2].filterItems = res.map(x => ({ value: x.STORAGE_CODE, text: x.STORAGE_NAME }));
    },
    async getFwhdSfList() {
      const res = await getFwhdSfList();
      this.columns[6].filterItems = res.map(x => ({ value: x.CHARGE_PARTITION_CODE, text: x.CHARGE_PARTITION_NAME }));
    },
    func(val, num) {
      if (val) {
        const res = this.columns[num].filterItems.find(x => x.value == val);
        return res.text;
      }
    },
    insertRecords(list) {
      console.log(list, 'erci');
      let arr = [];
      if (list && list.length > 0) {
        arr = list.map(x => ({ text: x.LABOUR_NAME, value: x.LABOUR_CODE + '~' + x.UID_HIDDEN }));
        console.log(arr, 'arr');
      }
      this.editItems = arr;
      console.log('维修项目数据：' + arr);
      console.log('维修项目数据：', arr);
      this.columns.find(x => x.dataIndex === 'LABOUR_CODE').editItems = this.editItems;
      this.propsList = list;
      // this.basetables.EXECUTE_INSERT(list);
    },
    changeSfqfHandleData(val) {
      console.log('更新维修项目的收费区分', val);
      let repairPart = this.onSyncTableData;
      for (var j = 0; j < repairPart.length; j++) {
        if (val.LABOUR_INDEX === repairPart[j].LABOUR_CODE) {
          if (val.CHARGE_PARTITION_CODE) {
            repairPart[j].CHARGE_PARTITION_CODE = val.CHARGE_PARTITION_CODE;
          } else {
            repairPart[j].CHARGE_PARTITION_CODE = '';
          }
        } else {
        }
      }
    }
  }
};
</script>
